package com.zycfc.zsf.boot.util.number;

import java.util.regex.*;

public abstract class UnitConverter
{
    private static final Pattern NUMBER_AND_UNIT;
    
    public static long convertDurationMillis(final String duration) {
        final Matcher matcher = UnitConverter.NUMBER_AND_UNIT.matcher(duration);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("malformed duration string: " + duration);
        }
        final long number = Long.parseLong(matcher.group(1));
        if (matcher.group(2) == null) {
            return number;
        }
        final String unitStr = matcher.group(2).toLowerCase();
        final char unit = unitStr.charAt(0);
        switch (unit) {
            case 's': {
                return number * 1000L;
            }
            case 'm': {
                if (unitStr.length() >= 2 && unitStr.charAt(1) == 's') {
                    return number;
                }
                return number * 60L * 1000L;
            }
            case 'h': {
                return number * 60L * 60L * 1000L;
            }
            case 'd': {
                return number * 60L * 60L * 24L * 1000L;
            }
            default: {
                throw new IllegalArgumentException("unknown time unit :" + unit);
            }
        }
    }
    
    public static long convertSizeBytes(final String size) {
        final Matcher matcher = UnitConverter.NUMBER_AND_UNIT.matcher(size);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("malformed size string: " + size);
        }
        final long number = Long.parseLong(matcher.group(1));
        if (matcher.group(2) == null) {
            return number;
        }
        final char unit = matcher.group(2).toLowerCase().charAt(0);
        switch (unit) {
            case 'b': {
                return number;
            }
            case 'k': {
                return number * 1024L;
            }
            case 'm': {
                return number * 1024L * 1024L;
            }
            case 'g': {
                return number * 1024L * 1024L * 1024L;
            }
            case 't': {
                return number * 1024L * 1024L * 1024L * 1024L;
            }
            default: {
                throw new IllegalArgumentException("unknown size unit :" + unit);
            }
        }
    }
    
    static {
        NUMBER_AND_UNIT = Pattern.compile("(\\d+)([a-zA-Z]+)?");
    }
}
